import pymysql
import logging

logger = logging.getLogger('log')
from myblog.models import MamahaoTestDatabase


def getSql(id, sql):
    try:
        database = MamahaoTestDatabase.objects.filter(id=id)
        host = database.values("host")[0]["host"]
        username = database.values("username")[0]["username"]
        password = database.values("password")[0]["password"]
        port = database.values("port")[0]["port"]
        connect = pymysql.Connect(
            host=str(host), user=str(username), passwd=str(password), port=int(port), charset='utf8'
        )
        # 获取游标
        cursor = connect.cursor()
        cursor.execute(sql)
        rawData = cursor.fetchall()
        col_names = [desc[0] for desc in cursor.description]
        result = []
        for row in rawData:
            objDict = {}
            # 把每一行的数据遍历出来放到Dict中
            for index, value in enumerate(row):
                objDict[col_names[index]] = value
            result.append(objDict)
        return result

    except  Exception as e:
        logger.error(e)
    finally:
        cursor.close()
        connect.close()
